<template>
  <div class="app-container">

    <!-- 表格查询 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">
      <el-form-item label="销售计划编号" prop="salePlanCode">
        <el-input
          v-model="queryParams.salePlanCode"
          placeholder="请输入销售计划编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售计划名称" prop="salePlanName">
        <el-input
          v-model="queryParams.salePlanName"
          placeholder="请输入销售计划名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="车型" prop="itemTypeId">
        <el-select v-model="queryParams.itemTypeId" placeholder="请选择车型" clearable>
          <el-option
            v-for="dict in productOptions"
            :key="dict.itemTypeId"
            :label="dict.itemTypeName"
            :value="dict.itemTypeId"
          />
        </el-select>
        </el-form-item>
        <el-form-item label="需求日期" prop="requireTime">
          <el-date-picker clearable
            v-model="queryParams.requireTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择需求日期">
          </el-date-picker>
        </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表头操作 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mes:pro:workorder:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="ids.length === 0"
          @click="handleDelete"
          >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleExport('in')"
          >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport('out')"
          >导出</el-button>
      </el-col>
    </el-row>

    <!-- 表格数据 -->
    <vxe-table
      border
      stripe
      ref="tableRef"
      size="small"
      header-align="center"
      :row-config="rowConfig"
      :column-config="columnConfig"
      @checkbox-change="checkboxChangeEvent"
      @checkbox-all="checkboxAll"
      @cell-click="cellClickEvent"
      :data="tableData"
      height="520"
    >
      <vxe-column type="checkbox" width="40" fixed="left"></vxe-column>
      <vxe-column type="seq" width="70" title="序号" drag-sort></vxe-column>
      <vxe-column field="salePlanCode" show-overflow="title" align="center" title="销售计划编号"></vxe-column>
      <vxe-column field="salePlanName" show-overflow="title" align="center" title="销售计划名称"></vxe-column>
      <vxe-column field="itemTypeName" width="100" show-overflow="title" align="center" title="车型"></vxe-column>
      <vxe-column field="quantity" width="100" show-overflow="title" align="center" title="数量合计"></vxe-column>
      <vxe-column field="unitOfMeasure" width="100" show-overflow="title" align="center" title="单位"></vxe-column>
      <vxe-column field="createBy" width="100" show-overflow="title" align="center" title="制单人"></vxe-column>
      <vxe-column show-overflow="title" align="center" title="制单日期">
        <template #default="{ row }">
          <span>{{ parseTime(row.createTime,'{y}-{m}-{d}') }}</span>
        </template>
      </vxe-column>
      <vxe-column show-overflow="title" align="center" title="需求日期">
        <template #default="{ row }">
          <span>{{ parseTime(row.requireTime,'{y}-{m}-{d}') }}</span>
        </template>
      </vxe-column>
      <!-- <vxe-column field="rtDate" width="100" show-overflow="title" align="center" title="单据状态"></vxe-column> -->
      <vxe-column field="remark" show-overflow="title" align="center" title="备注"></vxe-column>
      <vxe-column width="160" align="center" title="操作" fixed="right">
        <template #default="{ row }">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(row)"
          >修改</el-button>
        </template>
      </vxe-column>
    </vxe-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 底部表格 -->
    <div class="app-container-footer">
      <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick" :lazy="true">
        <el-tab-pane label="销售计划明细" name="1"><salesPlanDetail :salesPlanId="salesPlanId" :itemTypeId="itemTypeId" /></el-tab-pane>
      </el-tabs>
    </div>

    
    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <!-- 上传文件 -->
      <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
              <!-- <div class="el-upload__tip" slot="tip">
                  <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的设备数据
              </div> -->
              <span>仅允许导入xls、xlsx格式文件。</span>
              <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增弹窗 -->
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="1200px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="制单日期??" prop="requireTime">
              <el-date-picker clearable
                v-model="form.requireTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择制单日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售计划编码" prop="salePlanCode">
              <el-input v-model.trim="form.salePlanCode" :disabled="form.id?true:false" placeholder="请输入销售计划编码" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item  label-width="80">
              <el-switch 
                :disabled="form.salePlanCode != null"
                v-model="autoGenFlag"
                active-color="#13ce66"
                active-text="自动生成"
                @change="handleAutoGenChange(autoGenFlag)" >               
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="销售计划名称" prop="salePlanName">
              <el-input v-model.trim="form.salePlanName" placeholder="请输入供应商名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="车型" prop="itemTypeId">
              <el-select v-model="form.itemTypeId" placeholder="请选择车型" clearable>
                <el-option
                  v-for="dict in productOptions"
                  :key="dict.itemTypeId"
                  :label="dict.itemTypeName"
                  :value="dict.itemTypeId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="需求日期" prop="requireTime">
              <el-date-picker clearable
                v-model="form.requireTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择需求日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
              <el-form-item label="制单人" prop="bizUser">
                  <el-select v-model="form.bizUser" placeholder="请选择制单人">
                      <el-option
                          v-for="dict in userList"
                          :key="dict.userId"
                          :label="dict.userName"
                          :value="dict.nickName"
                      />
                  </el-select>
              </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="数量" prop="quantity">
              <el-input-number :min="0" v-model.trim="form.quantity" />
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model.trim="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listSalesPlan,
  addSalesPlan,
  editSalesPlan,
  delSalesPlan,
  importSalesPlan, 
  getListProduct
} from "@/api/mes/sales/salesPlan";
import { listUser } from "@/api/system/user";
import { genCode } from "@/api/system/autocode/rule";
import { getToken } from "@/utils/auth";
import salesPlanDetail from './components/salesPlanDetail.vue'

export default {
  name: 'salesPlan',
  components: { 
    salesPlanDetail 
  },
  data() {
    return {
      activeName: '1',
      autoGenFlag: false,
      tableData: [],
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        salePlanCode: null,
        salePlanName: null,
        itemTypeId: null,
        requireTime: null,
      },
      // 选中ids数组
      ids: [],
      // 非多个禁用
      multiple: true,
      columnConfig: {
        drag: true,
        resizable: true,
        storage: true,
        sortConfig: {
          trigger: 'cell',
          remote: true
        },
        align: 'center',
        headerAlign: 'center'
      },
      rowConfig: {
        drag: true,
        keyField: 'id',
        isHover: true,
        isCurrent: true,
      },
      title: '',
      form: {},
      open: false,
      rules: {
        salePlanCode: [
          { required: true, message: '请输入销售计划编号', trigger: 'blur' }
        ],
        salePlanName: [
          { required: true, message: '请输入销售计划名称', trigger: 'blur' }
        ],
        itemTypeId: [
          { required: true, message: '请选择车型', trigger: 'change' }
        ],
      },
      upload: {
        open: false,
        title: "",
        isUploading: false,
        updateSupport: 0,
        headers: { Authorization: "Bearer " + getToken() },
        url: process.env.VUE_APP_BASE_API + "/mes/sale/plan/importData"
      },
      productOptions: [],
      salesPlanId: null,
      itemTypeId: null,
      userList:[]
    } 
  },
  mounted() {
    this.getList()
    listUser({ pageNum: 1, pageSize: 9999 }).then(response => {
      this.userList = response.rows;
    })
  },
  methods: {
    selectRowEvent () {
      const $table = this.$refs.tableRef
      if ($table) {
        $table.setCurrentRow(this.tableData[0])
      }
    },
    getList(){
      this.tableData = []
      listSalesPlan(this.queryParams).then(res => {
        this.tableData = res.rows;
        this.salesPlanId = res.rows[0].id;
        this.itemTypeId = res.rows[0].itemTypeId;
        this.total = res.total;
        this.selectRowEvent()
        console.log(res);
      })
      getListProduct().then(res => {
        this.productOptions = res.data;
        console.log('getListProduct', res);
      })
    },
    handleAdd(){
      this.open = true;
      this.title = '新增销售计划';
      this.reset()
    },
    handleEdit(row){
      this.open = true;
      this.title = '修改销售计划';
      this.form = {...row};
      console.log(this.form,' :disabled=');
    },
    /** 删除按钮操作 */
    handleDelete() {
      const salePlanIds = this.ids
      if (salePlanIds.length === 0) {
        this.$modal.msgError("请选择要删除的数据")
        return
      }
      this.$modal.confirm('是否确认删除选中的' + salePlanIds.length + '条数据项？').then(() => {
        return delSalesPlan(salePlanIds)
      }).then(() => {
        this.ids = []
        this.multiple = true
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    handleExport(type){
      const salePlanIds = this.ids
      if(type === 'in'){
        this.upload.title = "数据导入";
        this.upload.open = true;
      } else {
        if(salePlanIds.length === 0){
          this.$modal.msgError("请选择要导出的数据")
          return 
        }
        this.$modal.confirm('是否确认导出选中的' + salePlanIds.length + '条数据项？').then(() => {
          return importSalesPlan(salePlanIds) 
        })
      }
    },
    reset(){
      this.form = {
        id: undefined,
        salePlanCode: undefined,
        salePlanName: undefined,
        itemTypeName: undefined,
        requireTime: undefined,
        remark: undefined,
      };
      // this.getList();
    },
    submitForm(){
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.productOptions.forEach(item => {
            if(item.itemTypeId==this.form.itemTypeId){
              this.form.itemTypeName = item.itemTypeName
            }
          })
          if (this.form.id) {
            editSalesPlan(this.form).then(res => {
              this.$message.success('修改成功');
              this.open = false;
              this.getList();
            })
          } else {
            addSalesPlan(this.form).then(res => {
              this.$message.success('新增成功');
              this.open = false;
              this.getList();
            })
          }
        }
      })
    },
    handleQuery(){
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery(){
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        salePlanCode: null,
        salePlanName: null,
        itemTypeId: null,
        requireTime: null,
      }
      this.getList();
      console.log('handleQuery');
    },
    checkboxChangeEvent(checked){
      this.ids = checked.records.map(item => item.id)
      console.log(checked.records, this.ids);
    },
    checkboxAll(checked){
      this.ids = checked.records.map(item => item.id)
      console.log(checked.records, this.ids)
    },
    cellClickEvent({row}){
      this.salesPlanId = row.id;
      this.itemTypeId = row.itemTypeId;
      this.handleClick({name:'1'})
      console.log(row);
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag){
      if(autoGenFlag){
        genCode('WORKORDER_CODE').then(response =>{
          this.form.salePlanCode = response;
        });
      }else{
        this.form.salePlanCode = null;
      }
    },
    cancel(){
      this.open = false;
      this.$refs.form.resetFields();
      this.reset();
    },
    handleClick(tab, event) {
      switch (tab.name) {
        case '1':
          console.log('销售计划明细');
          break;
        case '2':
          console.log('2');
          break;
        default:
          break;
      }
    },
    importTemplate(){
      window.open("/excel_templates/shop_templates.xls", "_blank"); 
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container{
  &-footer{
    margin-top: 20px;
  }
}
.el-select, .el-date-editor{
  width: 100%;
}
</style>